<template>
	<div class="w-full bet-amount" :class="isRuning ? 'opacity-50' : ''">
		<div class="text-[#96A5AA] text-base h-[18px] leading-[18px] moneybox f-style">
			<span class="text-[14px]">{{ $t('miniGames.amount') }}</span>

			<span class="text-[12px]">
				<base-amount :value="value" :currency="currency" hide-currency reverse-fiat />
			</span>
		</div>
		<n-popover
			:show="showTip"
			trigger="manual"
			@update:show="showTip = $event"
			open-delay="100"
			close-delay="100"
			:animated="false"
			:placement="isPC() ? 'top' : 'bottom'"
			v-bind="NBind.Popover">
			<template #trigger>
				<n-input-group
					class="mt-[4px] flex h-[40px] rounded-[4px] b-shadow"
					size="large"
					:style="{ pointerEvents: isRuning || isDisabled ? 'none' : '' }">
					<n-input
						class="flex-1 rounded-[4px] input-style"
						:class="{
							'!border-danger': showTip
						}"
						:disabled="isDisabled"
						v-model:value="value"
						:allow-input="onlyAllowNumber"
						:on-input="changeAmount"
						:on-focus="handleSelect"
						:on-blur="handleBlur"
						ref="inputInstRef">
						<template #suffix>
							<div
								class="flex items-center flex-col mr-6 text-[10px] w-[14px] rounded-[2px]"
								style="background-color: #3e4c68">
								<base-icon class="point" name="superior" @click="add" />
								<base-icon class="point" name="down" @click="down" />
							</div>
							<base-currency-fait />
						</template>
					</n-input>
					<n-input-group-label
						class="px-0 h-[40px] rounded-[4px] overflow-hidden"
						size="large"
						style="background-color: #3e4c68">
						<div class="h-[40px] flex justify-center items-center">
							<div
								class="w-[42px] h-[40px] flex justify-center items-center app-font-bold text-base cursor-pointer text-[14px] btn-style"
								@click="handleErfenzhiyi">
								<base-icon :size="12" name="erfenzhiyi" />
							</div>
							<div class="h-[20px] border-l-[1px] border-[#1B2538]"></div>
							<div
								class="w-[42px] h-[40px] flex justify-center items-center app-font-bold text-base cursor-pointer text-[14px] btn-style"
								@click="handleDoubble">
								<base-icon :size="18" name="2x" />
							</div>
							<div v-show="showMax" class="h-[20px] border-l-[1px] border-[#1B2538]"></div>
							<div
								v-show="showMax"
								class="w-[42px] h-[40px] flex justify-center items-center app-font-bold text-base cursor-pointer btn-style"
								@click="handleMax">
								{{ $t('miniGames.max') }}
							</div>
						</div>
					</n-input-group-label>
				</n-input-group>
			</template>
			<span>您的投注额不能大于余额</span>
		</n-popover>
	</div>
</template>
<script lang="ts" setup>
import { NInput, NInputGroup, NInputGroupLabel, NPopover } from 'naive-ui'
import { BaseIcon, BaseAmount, BaseCurrencyFait } from '@/components/base'
import { computed, ref, watch, onMounted } from 'vue'
import { useWalletStore } from '@/store'
import { isPC, Decimals } from '@/utils'
import type { InputInst } from 'naive-ui'
import { NBind } from '@/plugins/naive-ui'
import { getDecimalPlaces, transferToNumber } from '../../util'

const walletStore = useWalletStore()
// const profileStore = useProfileStore()

const currency = computed(() => walletStore.balanceCur?.currency)
const inputInstRef = ref<InputInst | null>(null)
const value = ref<any>('0')
const showTip = ref<boolean>(false)
const props = defineProps({
	isRuning: {
		type: Boolean,
		default: false
	},
	type: {
		type: String,
		default: ''
	},
	showMax: {
		type: Boolean,
		default: false
	},
	isDisabled: {
		type: Boolean,
		default: false
	},
	amount: {
		type: [Number, String],
		default: 0
	}
})
const onlyAllowNumber = (value: string) => !value || /^\d+(\.\d*)?$/.test(value)
const emit = defineEmits(['changeAmount', 'changeMoneyDisabled'])

watch(
	() => props.amount,
	(val: any) => {
		value.value = val
	}
)
watch(
	() => walletStore.walletConfig?.displayCryptoInFiat,
	() => {
		handleBlur()
	}
)
watch([value, () => walletStore.balanceCur?.currentAmount], ([newVal1, newVal2]) => {
	const currentAmount = newVal2 || 0
	if (Number(currentAmount) < Number(newVal1)) {
		showTip.value = true
	} else {
		showTip.value = false
	}
	emit('changeMoneyDisabled', showTip.value)
})
onMounted(() => {
	handleBlur()
})
// const handleMouseDown = (event: { preventDefault: () => void }) => {
// 	event.preventDefault()
// 	inputInstRef.value && inputInstRef.value.focus()
// }
const changeAmount = (val: string) => {
	emit('changeAmount', val)
}
const handleBlur = () => {
	const valFixed = value.value
		? transferToNumber(Number(value.value).toFixed(getDecimalPlaces()))
		: value.value
	value.value = String(valFixed)
	emit('changeAmount', valFixed)
}
const handleSelect = () => {
	inputInstRef.value?.select()
}
const add = () => {
	if (+value.value < 0) {
		return
	}
	value.value = Decimals.add(value.value, 1)
	const currentAmount = walletStore.balanceCur?.currentAmount || 0
	if (Number(currentAmount) < Number(value.value)) {
		value.value = String(currentAmount)
	}
	emit('changeAmount', value.value)
}
const down = () => {
	if (+value.value <= 0) {
		return
	}
	value.value =
		Decimals.sub(value.value, 1) > 0 ? transferToNumber(Decimals.sub(value.value, 1)) : 0
	emit('changeAmount', value.value)
}
function halveAndRound(number: any) {
	const min = 1 / Math.pow(10, getDecimalPlaces())
	// 检查结果是否小于 min
	if (number <= min) {
		const o = 0
		return o.toFixed(getDecimalPlaces())
	}
	// 将数字减半
	const halved = number / 2
	// 使用 toFixed 方法保留最多8位小数，并转换回数字
	let result: any = parseFloat(halved.toFixed(getDecimalPlaces()))
	if (result === 0) {
		return result.toFixed(getDecimalPlaces())
	}
	// 将结果转换为固定格式的字符串，避免科学记数法
	result = result.toFixed(getDecimalPlaces())
	// 返回结果
	return transferToNumber(result)
}
const handleErfenzhiyi = () => {
	if (props.isRuning) {
		return
	}
	value.value = halveAndRound(parseFloat(value.value)) + ''
	emit('changeAmount', value.value)
}

const handleDoubble = () => {
	if (props.isRuning) {
		return
	}
	if (Number(value.value) === 0) {
		value.value = transferToNumber(1 / Math.pow(10, getDecimalPlaces()))
	} else {
		value.value = transferToNumber(parseFloat(value.value || 0) * 2)
	}
	const currentAmount = walletStore.balanceCur?.currentAmount || 0
	if (Number(currentAmount) < Number(value.value)) {
		value.value = String(Number(currentAmount).toFixed(getDecimalPlaces()))
	}
	emit('changeAmount', value.value)
}

const handleMax = () => {
	if (props.isRuning) {
		return
	}
	value.value = 999 + ''
}
</script>
<style lang="scss" scoped>
.bet-amount {
	:deep(.n-input-group-label__border) {
		display: none;
	}
	.point {
		cursor: pointer;
		width: 10px;
		height: 10px;
	}
	.mr-6 {
		margin-right: 6px;
	}
	.moneybox {
		display: flex;

		justify-content: space-between;
		span {
			color: var(--text-396-a-5-aa, #96a5aa);
			font-size: 14px;
			font-style: normal;
			font-weight: 700;
			line-height: 18px; /* 128.571% */
		}
		span:nth-child(2) {
			font-size: 12px;
		}
	}
}
.f-style {
	font-weight: 600;
}
.input-style {
	border: 2px solid #3e4c68;
	:deep(.n-input__input > .n-input__input-el) {
		height: 100% !important;
	}
}
.b-shadow {
	box-shadow:
		0 1px 3px 0 rgba(0, 0, 0, 0.2),
		0 1px 2px 0 rgba(0, 0, 0, 0.12);
}
.btn-style {
	&:hover,
	&.active {
		background-color: #557086;
	}
}
</style>
